using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace Library_management_system
{
    public partial class BorrowManagementForm : Form
    {
        public BorrowManagementForm()
        {
            InitializeComponent();
            LoadBorrows();
        }

        private void LoadBorrows(string keyword = "")
        {
            using (SqlConnection conn = DatabaseConfig.GetConnection())
            {
                conn.Open();
                string sql = @"SELECT br.RecordID, b.Title AS BookTitle, r.Name AS ReaderName, br.BorrowDate, br.DueDate, br.ReturnDate 
                             FROM BorrowRecords br
                             JOIN Books b ON br.BookID = b.BookID
                             JOIN Readers r ON br.ReaderID = r.ReaderID";
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    sql += " WHERE b.Title LIKE @kw OR r.Name LIKE @kw";
                }
                SqlCommand cmd = new SqlCommand(sql, conn);
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    cmd.Parameters.AddWithValue("@kw", "%" + keyword + "%");
                }
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                dgvBorrows.DataSource = dt;
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            LoadBorrows(txtSearch.Text.Trim());
        }

        private void btnReturn_Click(object sender, EventArgs e)
        {
            if (dgvBorrows.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要标记的借阅记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (dgvBorrows.SelectedRows[0].Cells["ReturnDate"].Value != DBNull.Value)
            {
                MessageBox.Show("该书已归还，无需重复操作！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int recordId = Convert.ToInt32(dgvBorrows.SelectedRows[0].Cells["RecordID"].Value);
            if (MessageBox.Show("确定要将该记录标记为已还吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                using (SqlConnection conn = DatabaseConfig.GetConnection())
                {
                    conn.Open();
                    string sql = "UPDATE BorrowRecords SET ReturnDate=@ReturnDate WHERE RecordID=@id";
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@ReturnDate", DateTime.Now);
                    cmd.Parameters.AddWithValue("@id", recordId);
                    cmd.ExecuteNonQuery();
                }
                LoadBorrows();
            }
        }
    }
}